class Store {
	constructor(options) {
		this._vm = new Vue({
			data: {
				state: options.state
			}
		});

		let getters = options.getters;
		this.getters = {};
		Object.keys(getters).forEach((val) => {
			Object.defineProperty(this.getters, val, { //getters响应式
			get: () => {
				return getters[val](this.state)
			}
			})
		})

		this._actions = Object.assign({}, options.actions)
		this._mutations = Object.assign({}, options.mutations)
	}

	// get/set state目的：防止外部直接修改state
	get state() {
		return this._vm.state
	}
	set state(value) {
		console.error('please use replaceState to reset state')
	}

	commit = (funName, params) => { //this执行问题
		// 在mutations中找到funName中对应的函数并且执行
		this._mutations[funName](this.state, params)
	}

	dispatch(funName, params) {
		this._actions[funName](this, params)
	}
}

function install(vue) {
	vue.mixin({
		beforeCreate () {
			const options = this.$options;
			
			if (options.storeTest) {//根组件;// 将 new Store() 实例挂载到唯一的根组件 this 上
				this.$storeTest = this.$options.storeTest;
			} else if(options.parent && options.parent.$storeTest) {//子组件
				this.$storeTest = this.$parent && this.$parent.$storeTest;
			}
		}
	})
}

export default {
	Store,
	install
}